package com.eascs.demand.controller;

import java.text.Format;
import java.text.SimpleDateFormat;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.UrlUtil;
import com.eascs.demand.entity.FormDemandEntity;
import com.eascs.demand.entity.MainApply;
import com.eascs.demand.entity.UserDemand;
import com.eascs.demand.service.DemandService;
import com.eascs.demand.service.TicketMainApplyService;
import com.eascs.site.page.CellWidthFormat;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;

@Controller
public class TicketDemandViewController extends BaseMasterViewController {

	// systemSettings
	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "systemSettings");
	}

	@Value("${o2o.admin.agreeUrlShow}")
	private String agreeUrlShow;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Inject
	private DemandService demandService;
	@Inject
	TicketMainApplyService ticketMainApplyService;
	@Autowired
	O2oPubDdItemService ddItemService;

	// 增加需求UI
	@RequestMapping("/demand/add")
	public String addApplyView() {
		return "/demand/add";
	}

	//
	@RequestMapping("/demand/viewDemand/{demandId}")
	public String viewDemand(@PathVariable String demandId) {
		UserDemand userDemand = new UserDemand();
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(demandId);
		// 如果传过来的是id，则根据id查询，如果传过来的是billcode，则根据billcode查询userDemand
		if (!"PDR".equals(demandId.split("-")[0])) {
			userDemand = demandService.getUserDemandById(demandId);
		} else {
			userDemand = demandService.getUserDemandByBillcode(demandId);
		}
		String demandType = userDemand.getDemandType();
		String processType = ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP;
		// Date createDate = userDemand.getCreateDate();
		// String agreeUrl =
		// baseUtils.getApprovalAgreeUrl(ticketMainApplyService.findMainApplyByExpandId(demandId).getMainapplyNo(),
		// null, SystemModule.SYSTEM_MODULE_O2O);
		// 如果是20170105之后创建的
		// SimpleDateFormat formatter = new
		// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// ParsePosition pos = new ParsePosition(0);
		// Date strtodate = formatter.parse("2017-01-05 20:25:25", pos);
		// if(createDate.after(strtodate)){
		// processType =ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP;
		// }else
		String itemtype = ddItemService.findPubdditemO2ONameByCode("SYSDEMANDTYPE", demandType);
		if ("SYSERR".equals(demandType) || "XTZX".equals(demandType) || "DJXG".equals(demandType) || "OTH".equals(demandType) || "EXDATA".equals(demandType)) {
			// 如果是系统需求申请：系统错误、系统咨询、单据修改、其它
			processType = ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP;
		} else if ("QXCL".equals(demandType) || "GNBG".equals(demandType) || "MBI".equals(demandType)) {
			// 如果是业务需求申请：权限处理，功能新增/变更/建议，基础信息维护
			processType = ProcessTemplate.PROECESS_TYPE_BUS_REQUIREMENT_APP;
		} else if ("DJZF".equals(demandType)) {
			// 如果是需求申请（只需要过总部领导的）:作废
			processType = ProcessTemplate.PROECESS_TYPE_HQ_REQUIREMENT_APP;
		} else if ("SYSDEVELOP".equals(demandType)) {
			// 如果是系统开发
			processType = ProcessTemplate.PROECESS_TYPE_SYSTEM_DEV;
		} else if (!StringUtils.isEmpty(itemtype)) {
			processType = demandType;
		}

		String agreeUrl = agreeUrlShow + ticketMainApplyService.findMainApplyByExpandId(demandId).getMainapplyNo() + "&processType=" + processType;
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("userDemand", userDemand);
		ViewContext.put("datalistInfo", getDatalistInfo(userDemand.getBillCode(), demandId));
		ViewContext.put("billStatus", mainApply.getBillStatus());
		return "/demand/view";
	}

	@RequestMapping(value = "/demand/datalist")
	public PaginationRestResult getOaBasicData(String demandNo) {
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(demandNo);
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "");
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		datalistInfo.setRendTo("#o2o_file");
		return PaginationRestResult.buildPaginationRestResult(datalistInfo);
	}

	/**
	 * 附件列表
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String demandNo, String demandId) {
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(demandId);
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(demandNo);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		// AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] { new
		// AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		if (mainApply != null) {
			Button delbutton = ButtonHelper.createAjaxButton("删除", "/loanrest/delete/");
			delbutton.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object arg0) {
					// Object []param = (Object[]) arg0;
					if (("NEW").equals(mainApply.getBillStatus()) || ("BH").equals(mainApply.getBillStatus())) {
						return true;
					}
					return false;
				}
			});
			Button[] detailButton = new Button[] { delbutton };
			datalistInfo.setMoreButtons(detailButton);
		}
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		return datalistInfo;
	}

	// 申请需求
	@RequestMapping("/demand/search")
	public String searchDemand(FormDemandEntity entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "xqsq");
		entity.setPageSize(10);
		String url = "/demand/search";
		User user = UserHolder.getUser();
		String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
		String demandUser = entity.getDemandUser() == null ? "" : entity.getDemandUser();
		String title = entity.getTitle() == null ? "" : entity.getTitle();
		String keyWord = entity.getKeyWord() == null ? "" : entity.getKeyWord();
		String applyStatus = entity.getApplyStatus() == null ? "" : entity.getApplyStatus();
		String beganTime = entity.getBeganTime() == null ? "" : entity.getBeganTime().toString();
		String endTime = entity.getEndTime() == null ? "" : entity.getEndTime().toString();
		boolean queryAll = entity.isQueryAll();
		url = UrlUtil.appendUrl(url, "bill_code", billCode);
		url = UrlUtil.appendUrl(url, "demandUser", demandUser);
		url = UrlUtil.appendUrl(url, "title", title);
		url = UrlUtil.appendUrl(url, "keyWord", keyWord);
		url = UrlUtil.appendUrl(url, "applyStatus", applyStatus);
		url = UrlUtil.appendUrl(url, "beganTime", beganTime);
		url = UrlUtil.appendUrl(url, "endTime", endTime);
		if (queryAll) {
			url = UrlUtil.appendUrl(url, "queryAll", queryAll + "");
		}
		url = url + "&showO2oPage=";
		/**
		 * 数据权限： 超级管理员能查看所有人的需求申请 其他人只能看到本人的需求申请单据
		 */
		if (!user.isSuperAdministrator()) {
			entity.setUserId(user.getNo());
		}
		PageResult<Object[]> pageResult = demandService.findByPageList(entity);
		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("SYSDEMANDTYPE"), null, null, null, null, null, new SelectDataOption("LCZT") };
		String[] titles = { "单据号", "标题", "需求类型", "需求人", "部门", "需求提出日期", "要求完成日期", "创建人", "状态", "流程结束日期" };
		Button[] findButton = new Button[] { ButtonHelper.createAjaxButton(null, "/demand/viewDemand?billCode=billCode&demandId="), null };

		Button starbutton = ButtonHelper.createAjaxButton("启动流程", "/demand/startup?demandid=");
		starbutton.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object arg0) {
				Object[] param = (Object[]) arg0;
				if (("NEW").equals(param[10]) || ("BH").equals(param[10])) {
					return true;
				}
				return false;
			}
		});

		Button exitbutton = ButtonHelper.createAjaxButton("收回", "/demand/cancel?demandid=");
		exitbutton.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object arg0) {
				Object[] param = (Object[]) arg0;
				if (("N").equals(param[1]) && ("RUN").equals(param[10]) && false) {
					return true;
				}
				return false;
			}
		});

		Button delbutton = ButtonHelper.createAjaxButton("删除", "/demand/del?demandid=");
		delbutton.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object arg0) {
				Object[] param = (Object[]) arg0;
				if (("N").equals(param[1]) && !("RUN").equals(param[10]) && !("CLO").equals(param[10])) {
					return true;
				}
				return false;
			}
		});

		Button[] detailButton = new Button[] { starbutton, exitbutton, delbutton };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setTitleButtons(findButton);
		paginationInfo.setMoreButtons(detailButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(2);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, new CellWidthFormat(300), null, null, null, new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy-MM-dd"), null, null, new SimpleDateFormat("yyyy-MM-dd") });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", entity);

		return "/demand/demandList";
	}

}
